package com.cb.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cb.entity.OutStore;
import com.cb.entity.Product;
import com.cb.mapper.ProductMapper;
import com.cb.service.OutStoreService;
import com.cb.mapper.OutStoreMapper;
import com.cb.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class OutStoreServiceImpl extends ServiceImpl<OutStoreMapper, OutStore> implements OutStoreService{

    @Autowired
    private OutStoreMapper outStoreMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public Result saveOutStore(OutStore outStore) {
        outStore.setTallyId(outStore.getCreateBy());
        outStore.setOutPrice(outStore.getSalePrice());
        outStore.setCreateTime(new Date());
        outStore.setIsOut("0");
        int insert = baseMapper.insert(outStore);
        if(insert>0){
            return Result.ok("添加出库单成功！");
        }else {
            return Result.err(Result.CODE_ERR_BUSINESS, "添加出库单失败！");
        }
    }

    @Override
    public IPage<OutStore> outStorePage(Page<OutStore> outStorePage, OutStore outStore) {
        return outStoreMapper.outStorePage(outStorePage,outStore);
    }

    @Override
    public Result confirmOutStore(OutStore outStore) {
        //根据商品id查询商品
        Product product = productMapper.selectById(outStore.getProductId());
        if(outStore.getOutNum()>product.getProductInvent()){
            return Result.err(Result.CODE_ERR_BUSINESS, "商品库存不足");
        }
        //根据id将出库单状态改为已出库
        LambdaUpdateWrapper<OutStore> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(OutStore::getOutsId,outStore.getOutsId()).set(OutStore::getIsOut,1);
        int update = baseMapper.update(null, updateWrapper);
        if(update<=0){
            return Result.err(Result.CODE_ERR_BUSINESS, "出库失败！");
        }
        //根据商品id减商品库存
        LambdaUpdateWrapper<Product> updateWrapper1 = new LambdaUpdateWrapper<>();
        updateWrapper1.eq(Product::getProductId,outStore.getProductId())
                .setSql("product_invent=product_invent-"+outStore.getOutNum());
        int update1 = productMapper.update(null, updateWrapper1);
        if(update1>0){
            return Result.ok("出库成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "出库失败！");
    }
}




